import { flattenDeep } from 'lodash'
import { Notice } from 'view-design'
import Cookie from 'js-cookie'
import store from '@/store'
import { toLoginPage, getToken, identities, getUserInfo, LogOut } from '@/api/user'
import { getNums } from '@/api/mq-service'
import config from '@/config/index'
export const platformLogin = (next) => {
    const url = location.href
    let Lurl = ''
    if (url.indexOf('?') > -1 && (url.indexOf('code=') > -1) || url.indexOf('token=') > -1) {
        Lurl = url.split('?')[0]
        const data = url.split('?')[1].split('&')
        const params = {}
        for (let i = 0; i < data.length; i++) {
            const str = data[i].split('=')
            params[str[0]] = str[1]
        }
        const { token, code } = params
        if (token) {
            getInit(token)

            next && next()
            return
        }

        getToken({ code, grantType: 'token' })
            .then(({ data }) => {
                getInit(data.token).then(() => {
                    // 登录成功，导航守卫放行
                    next('/')
                    location.href = Lurl
                })

            })
            .catch((err) => {
                if (err.errorcode == 400) {
                    toLoginPage({ redirectUri: encodeURIComponent(Lurl) })
                        .then(({ data }) => {
                            console.log(data)
                        })
                        .catch(err => {
                            console.log(err)
                        })
                    console.log('code过期')
                }
            })
    } else {
        // 退出
        webLogOut()
            //     // 回去登录
        var refreshUrl = url.split('#')[0] + '#/'
        toLoginPage({ redirectUri: encodeURIComponent(refreshUrl) })
            .then(({ data }) => {
                // 防止再次设置的refreshTime导致退出登录问题
                localStorage.clear()

                location.href = data
            })
            .catch(err => console.log(err))
    }
}
const webLogOut = () => {
    updateToken()

    localStorage.clear()

    store.commit('setAccess', [])

    store.commit('setUserInfo', {})

    store.commit('setInformation', null)

}

export const platformLogout = () => {
    const { userCode } = store.state.user.userInfo
    LogOut({ account: userCode })
        .finally(_ => {
            updateToken()

            localStorage.clear()

            store.commit('setAccess', [])

            store.commit('setUserInfo', {})

            store.commit('setInformation', null)

            location.href = location.href.split('#')[0] + '#/'

            platformLogin()
        })
}

export const getInit = async(token) => {
        await updateToken(token) // 更新token
        await userInfo()
        return;
        // 获取用户信息
        // userInfo();
        // permissionlist();
        // getUnreadNums();
        // updateToken(token);
    }
    // 获取站内信未读消息条数
export const getUnreadNums = async(type = 2) => {
    try {
        const { userId: receiveId, Information: old_num } = store.state.user,
            data = { receiveId, viewType: type }
        const { data: num } = await getNums(data)
            // 未读消息提醒
        if (type === 2) {
            (old_num !== null && old_num < num) && Notice.info({ title: '站内信通知提醒', desc: '您收到一条新的站内信通知，请及时查看' })
            store.commit('setInformation', num)
        }
        return num
    } catch (err) {
        console.log(err)
    }
}
const updateToken = (token = '') => {
    const cookieData = { path: '/', expires: 1 }

    Cookie.set('token', token, cookieData)
    store.commit('setToken', token)
}

export const permissionlist = async() => {
    try {
        const { data } = await identities()
        await store.commit('setAccess', flattenDeep(
            Object.keys(data.permissions).map(key => data.permissions[key])))
        await store.commit('setIdentities', data.identities)
    } catch (err) {
        console.log(err)
    }
}

export const userInfo = async() => {
    try {
        const { data } = await getUserInfo()
        store.commit('setUserId', data.id)
        store.commit('setUserName', data.userName)
        store.commit('setUserInfo', data)

        store.commit('setAvatar', data.portrait)
        localStorage.setItem('user_id', data.id)
        localStorage.setItem('mainUserId', data.mainUserId)
        await permissionlist() // 获取权限
        return
    } catch (err) {
        console.log(err)
    }
}
export const userInfo2 = async() => {
    try {
        const { data } = await getUserInfo()
        store.commit('setUserId', data.id)
        store.commit('setUserName', data.userName)
        store.commit('setUserInfo', data)

        store.commit('setAvatar', data.portrait)
        localStorage.setItem('user_id', data.id)
        localStorage.setItem('mainUserId', data.mainUserId)
        permissionlist() // 获取权限
    } catch (err) {
        console.log(err)
    }
}



var timer;
var num = 0;
const reconnect = () => {
        if (num >= 3) {
            console.log('结束了')
            return;
        }
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            webScokeLink()
        }, 3000)
    }
    // 动态站内信 eventSource
export const webScokeLink = () => {
    const { userId: receiveId } = store.state.user;
    var url =
        process.env.NODE_ENV == "development" ?
        config.baseUrl.dev :
        process.env.NODE_ENV == "testing" ?
        config.baseUrl.test :
        config.baseUrl.pro;
    var postURL =
        url + "/platform-msgs/internal-api/sse/connect/" + receiveId + 'm';
    var source = new EventSource(postURL, { withCredentials: true });
    source.addEventListener(
        "open",
        function(e) {
            console.log("建立连接。。。");
        },
        false
    );
    source.onmessage = function(data) {
        if (data.data == 1) {
            getNums({ receiveId, viewType: 2 }).then((res) => {
                store.commit("setInformation", res.data)
                Notice.info({
                    title: "站内信通知提醒",
                    desc: "您收到一条新的站内信通知，请及时查看",
                });
            });
            console.log(source, '...source')
        }
        //代码块
    };
    source.onerror = function() {
        console.log("项目Eventsource链接失败");
        //链接失败后EventSource会每隔三秒左右重新发起链接
        // 重连
        num++;
        reconnect()
    };
}